package db

import (
	"beego/comm/source"
	"context"
	"fmt"

	"github.com/astaxie/beego"
	"github.com/olivere/elastic"
)

func getESClient() *elastic.Client {
	es := source.Src.GetEsInfo()
	ipaddr := fmt.Sprintf("http://%s:%s", es["ip"], es["port"])
	client, err := elastic.NewClient(
		elastic.SetSniff(false),
		elastic.SetURL(ipaddr),
		elastic.SetBasicAuth(es["usr"], es["pwd"]))
	if nil != err {
		panic("ElasticSearch连接: " + err.Error())
	}
	return client
}

func EsInsert(esindex, estype, esid, data string) {
	client := getESClient()
	_, err := client.Index().
		Index(esindex).
		Type(estype).
		Id(esid).
		BodyJson(data).
		Do(context.Background())
	if nil != err {
		panic("ElasticSearch插数: " + err.Error())
	}
}

func EsDelete(esindex, estype, esid string) {
	client := getESClient()
	_, err := client.Delete().
		Index(esindex).
		Type(estype).
		Id(esid).
		Do(context.Background())
	if nil != err {
		panic("ElasticSearch删数: " + err.Error())
	}
}

func init() {
	beego.Info("测试连接ES...")
	getESClient()
	beego.Info("ES连接测试完成")
}
